package com.lottoad.android.activity.mypage;

import org.w3c.dom.Element;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.lottoad.android.R;
import com.lottoad.android.common.BaseActivity;
import com.lottoad.android.cronos.http.CNLottoAdApiSetEx;
import com.lottoad.android.util.ApplicationUtils;
import com.lottoad.android.util.CNCronosLog;
import com.lottoad.android.util.LottoAdOverButton;

/**
 * MyPage -  이체신청 Activity
 * @author Administrator
 *
 */
public class LottoAdMypageCashOutActivity extends BaseActivity{
	private Context mContext;
	
	/** 예금주 명 **/
	private EditText mNameEdit;
	/** 은행 명 **/
	private EditText mBankEdit;
	/** 계좌번호 **/
	private EditText mNumberEdit;
	/** 이체신청 금액 **/
	private EditText mMoneyEdit;
	
	/** 총 누적 금액(이체신청 가능금액) **/
	private TextView mNujukTv;
	
	String tmpMoneyStr = "";
	
	private Button mCashOutBtn;
	
	private String mName;
	private String mBank;
	private String mNumber;
	private String mMoneyStr;
	
	private int mMoney = 0;
	private String mUsableMoney;
	
	@Override
	protected int onGetContentViewResource() {
		return R.layout.lottoad_menu_mypage_cashout;
	}

	@Override
	protected void onInit() {
		this.mContext = getParent();
	}
	
	private void buildComponent(){
		Intent intent = getIntent();
		
		mUsableMoney = intent.getStringExtra("usable");  
		
		mNujukTv = (TextView) findViewById(R.id.textView_nujuk);
		
		mNameEdit = (EditText) findViewById(R.id.editText_name);
		mBankEdit = (EditText) findViewById(R.id.editText_bank);
		mNumberEdit = (EditText) findViewById(R.id.editText_number);
		mMoneyEdit = (EditText) findViewById(R.id.editText_money);
		
		mNujukTv.setText(mUsableMoney + " 원");
		
		mMoneyEdit.addTextChangedListener(new TextWatcher() {
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

				// 숫자가 추가되었을때에 Comma를 추가해준다.
				if (!s.toString().equals(tmpMoneyStr)) {

					// 숫자에 Comma를 추가해주는 메소드 호출
					tmpMoneyStr = ApplicationUtils.makeStringWithComma(s.toString().replace(",", ""), true);
					mMoneyEdit.setText(tmpMoneyStr);
					Editable e = mMoneyEdit.getText();
					// 커서의 위치가 현재 입력된 위치의 끝쪽에 가게 해야 한다.

					Selection.setSelection(e, tmpMoneyStr.length());
				}
			}

			public void afterTextChanged(Editable s) {
				
			}
		});
		
		mCashOutBtn = (Button) findViewById(R.id.button_cashoutput);
		
		mCashOutBtn.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				Drawable getBackground = v.getBackground();
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					v.setBackgroundDrawable(LottoAdOverButton
							.grayimg(getBackground));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					getBackground.clearColorFilter();
					v.setBackgroundDrawable(getBackground);
					if (mNameEdit.getText().toString().equals("")
							|| mBankEdit.getText().toString().equals("")
							|| mNumberEdit.getText().toString().equals("")
							|| mMoneyEdit.getText().toString().equals("")) {
						ApplicationUtils.showOkDialog(mContext, 0,
								getString(R.string.popup_alert),
								"정보를 모두 입력해주세요.");
					} else {
						int money = Integer.parseInt(mMoneyEdit.getText().toString().replace(",", ""));
						if (money < 10000) { 
							ApplicationUtils.showOkDialog(mContext, 0,
									getString(R.string.popup_alert),
									"10,000원 이상만 입금신청이 가능합니다.");
						} else if (money > Integer.parseInt(mUsableMoney.replace(",",""))) {
							ApplicationUtils.showOkDialog(mContext, 0,
									getString(R.string.popup_alert),
									"현재 보유한 적립 금액을 초과하여 입력 할 수 없습니다.");
						} else {
							if(money % 10000 == 0){
								onRequestData();
							} else {
								ApplicationUtils.showOkDialog(mContext, 0,
										getString(R.string.popup_alert),
										"10,000원 단위로 입금신청이 가능합니다.");
							}
						}
					}
				}
				return false;
			}
		});
	}
	
	@Override
	public String onGetAsyncRequestUrl() {
		CNCronosLog.d("onGetAsyncRequestUrl()");
		String url = null;
		
		mName = mNameEdit.getText().toString();
		mBank = mBankEdit.getText().toString();
		mNumber = mNumberEdit.getText().toString();
		mMoneyStr = mMoneyEdit.getText().toString();
		if(mMoneyStr != null && !mMoneyStr.equals("") && mMoneyStr.length() > 0)
			mMoney = Integer.parseInt(mMoneyStr.replace(",", "").substring(0, mMoneyStr.replace(",", "").length()));
		
		CNLottoAdApiSetEx MnetGlobalApiSetEx = CNLottoAdApiSetEx.getInstance();
		url = MnetGlobalApiSetEx.setTransferUrl(mContext, mName, mBank, mNumber, ApplicationUtils.getPhoneNumber(mContext), mMoney);
		CNCronosLog.d("onGetAsyncRequestUrl", "url : "+url);
		return url;
	}
	
	@Override
	public void onAsyncCancelRequest() 
	{
		super.hideLoadingDialog();
		CNCronosLog.d("onAsyncCancelRequest()");
	}

	@Override
	public void onAsyncDataError(Element xmlObject, String errorMessage)
	{
		super.hideLoadingDialog();
		
		ApplicationUtils.showOkDialog(mContext, 0, "알림", errorMessage);
	}

	@Override
	public void onAsyncPreRequest()
	{
		super.showLoadingDialog(mContext);
	}

	@Override
	public void onAsyncRequestCompleted(Element xmlObject)
	{
		super.hideLoadingDialog();
		
		try {
			ApplicationUtils.showOkDialog(mContext, 0, getString(R.string.mypage_cashout_title), getString(R.string.mypage_cashout_contents), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					onBackPressed();
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onAsyncRequestError(int errorNumber) {
		super.hideLoadingDialog();
		
		ApplicationUtils.showOkDialog(mContext,0,getString(R.string.popup_alert), ApplicationUtils.getErrorMessage(mContext, errorNumber));
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		buildComponent();
	}
	
	@Override
	public void onBackPressed() {
		((LottoAdMyPageGroupActivity)getParent()).onBackPressed();
	}
}
